package com.xiaopo.flying.sticker;

import ohos.aafwk.ability.DataAbilityHelper;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.RectFloat;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.data.rdb.ValuesBucket;
import ohos.data.resultset.ResultSet;
import ohos.media.image.ImagePacker;
import ohos.media.image.PixelMap;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import static java.lang.Math.round;

/**
 * @author wupanjie
 */
class StickerUtils {
    public static void saveImageToGallery(PixelMap pixelMap, Context context) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA);
            String filename = simpleDateFormat.format(new Date());

            ValuesBucket valuesBucket = new ValuesBucket();
            valuesBucket.putString(AVStorage.Images.Media.DISPLAY_NAME, filename);
            valuesBucket.putString("relative_path", "DCIM/");
            valuesBucket.putString(AVStorage.Images.Media.MIME_TYPE, "image/JPEG");
            //应用独占
            valuesBucket.putInteger("is_pending", 1);
            DataAbilityHelper helper = DataAbilityHelper.creator(context);
            int id = helper.insert(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, valuesBucket);
            Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, String.valueOf(id));
            //这里需要"w"写权限
            FileDescriptor fd = helper.openFile(uri, "w");
            ImagePacker imagePacker = ImagePacker.create();
            ImagePacker.PackingOptions packingOptions = new ImagePacker.PackingOptions();
            OutputStream outputStream = new FileOutputStream(fd);
            boolean result = imagePacker.initializePacking(outputStream, packingOptions);
            DirectionalLayout toastLayout = (DirectionalLayout) LayoutScatter.getInstance(context)
                .parse(ResourceTable.Layout_layout_toast, null, false);
            Text textDialog = (Text) toastLayout.findComponentById(com.xiaopo.flying.sticker.ResourceTable.Id_msg_toast);
            if (result) {
                result = imagePacker.addImage(pixelMap);
                if (result) {
                    imagePacker.finalizePacking();
                }
                ResultSet resultSet = helper.query(uri, new String[]{AVStorage.Images.Media.DATA}, null);
                while (resultSet != null && resultSet.goToNextRow()) {
                    // 获取图片的绝对路径
                    String dataUrl = resultSet.getString(resultSet.getColumnIndexForName(AVStorage.Images.Media.DATA));
                    textDialog.setMultipleLine(true);
                    textDialog.setText("saved in " + dataUrl);
                    new ToastDialog(context)
                        .setContentCustomComponent(toastLayout)
                        .setAlignment(LayoutAlignment.BOTTOM)
                        .setOffset(0, 200)
                        .show();
                }
            } else {
                textDialog.setText("the file is null");
                new ToastDialog(context)
                    .setContentCustomComponent(toastLayout)
                    .setAlignment(LayoutAlignment.BOTTOM)
                    .setOffset(0, 200)
                    .setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT)
                    .show();
            }
            outputStream.flush();
            outputStream.close();
            valuesBucket.clear();
            //解除独占
            valuesBucket.putInteger("is_pending", 0);
            helper.update(uri, valuesBucket, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static RectFloat trapToRect(float[] array) {
        RectFloat r = new RectFloat();
        trapToRect(r, array);
        return r;
    }

    public static void trapToRect(RectFloat r, float[] array) {
        r.left = Float.POSITIVE_INFINITY;
        r.top = Float.POSITIVE_INFINITY;
        r.right = Float.NEGATIVE_INFINITY;
        r.bottom = Float.NEGATIVE_INFINITY;
        for (int i = 1; i < array.length; i += 2) {
            float x = round(array[i - 1] * 10) / 10.f;
            float y = round(array[i] * 10) / 10.f;
            r.left = (x < r.left) ? x : r.left;
            r.top = (y < r.top) ? y : r.top;
            r.right = (x > r.right) ? x : r.right;
            r.bottom = (y > r.bottom) ? y : r.bottom;
        }
        if (r.left > r.right) {
            float temp = r.left;
            r.left = r.right;
            r.right = temp;
        }
        if (r.top > r.bottom) {
            float temp = r.top;
            r.top = r.bottom;
            r.bottom = temp;
        }
    }
}
